ui.js ➔ enable_provider   F
last analyzed

Complexity

Conditions 28

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 30
rs 0
c 0
b 0
f 0
cc 28

How to fix   Complexity   

Complexity

Complex classes like ui.js ➔ enable_provider often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
const org_openpsa_layout = {
2
    clip_toolbar: function() {
3
        if ($('#org_openpsa_toolbar > ul.view_toolbar').length === 0) {
4
            // there seem to be no toolbar buttons, so we don't need to do anything
5
            return;
6
        }
7
        var container = $('#toolbar_dropdown').length > 0 ? $('#toolbar_dropdown') : $('<li class="enabled submenu"><a><i class="fa fa-caret-down"></i> <span class="toolbar_label">' + TOOLBAR_MORE_LABEL + '</span></a><ul class="midcom_toolbar"></ul></li>')
8
            .attr('id', 'toolbar_dropdown')
9
            .data('event_attached', false)
10
            .mouseover(function() {
11
                var self = $(this);
12
                if (self.data('timeout')) {
13
                    clearTimeout(self.data('timeout'));
14
                    self.removeData('timeout');
15
                    return;
16
                }
17
                self.addClass('expanded');
18
            })
19
            .mouseout(function() {
20
                var self = $(this);
21
                self.data('timeout', setTimeout(function() {
22
                    self.removeClass('expanded');
23
                    self.removeData('timeout');
24
                }, 500));
25
            })
26
            .css('display', 'none')
27
            .appendTo('#org_openpsa_toolbar > ul.view_toolbar'),
28
29
            dropdown = container.find('ul.midcom_toolbar'),
30
            toolbarWidth = $('#org_openpsa_toolbar').width() - ($('#org_openpsa_toolbar .navigation_toolbar').width() || 0),
31
            over = false;
32
33
        $('#org_openpsa_toolbar > .view_toolbar > li:not(#toolbar_dropdown)').each(function() {
34
            if (!over && ($(this).position().left + $(this).width() + container.width()) > toolbarWidth) {
35
                over = true;
36
            }
37
            if (over) {
38
                if (!container.data('event_attached')) {
39
                    dropdown.append($(this).detach());
40
                } else {
41
                    dropdown.prepend($(this).detach());
42
                }
43
            }
44
        });
45
        if (!over) {
46
            dropdown.children('li:not(#toolbar_dropdown)').each(function() {
47
                var item = $(this)
48
                    .clone()
49
                    .css('visibility', 'hidden')
50
                    .insertBefore(container),
51
52
                    positionLast = $('#org_openpsa_toolbar .view_toolbar li:last-child').position().left + $('#org_openpsa_toolbar .view_toolbar li:last-child').width();
53
54
                if (positionLast < toolbarWidth) {
55
                    $(this).remove();
56
                    item.css('visibility', 'visible');
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
57
                } else {
58
                    item.remove();
59
                    return false;
60
                }
61
            });
62
        }
63
64
        if (dropdown.children('li').length > 0) {
65
            container.css('display', 'inline-block');
66
        } else {
67
            container.css('display', 'none');
68
        }
69
        if (!container.data('event_attached')) {
70
            $(window).resize(function(){org_openpsa_layout.clip_toolbar();});
71
            container.data('event_attached', true);
72
            container.parent().addClass('clip-initialized');
73
        }
74
    },
75
76
    add_splitter: function() {
77
        $('<div></div>')
78
            .attr('id', 'template_openpsa2_resizer')
79
            .css('left', $('#leftframe').width())
80
            .appendTo('#container');
81
82
        $('#template_openpsa2_resizer').draggable({
83
            axis: 'x',
84
            containment: 'window',
85
            stop: function(event, ui) {
86
                var offset = Math.max((ui.offset.left), 0);
87
88
                $('#leftframe').css('width', offset + 'px');
89
90
                $.post(MIDCOM_PAGE_PREFIX + '__mfa/asgard/preferences/ajax/', {openpsa2_offset: offset + 2});
91
                $(window).trigger('resize');
92
            }
93
        });
94
    },
95
96
    initialize_search: function(providers, config) {
97
        if (typeof providers !== 'object' || providers.length === 0) {
98
            return;
99
        }
100
        
101
        let defaults = {
102
            field: '#org_openpsa_search_query',
103
            current: providers[0].identifier
104
        };
105
106
        if (typeof config === 'string'){
107
            config = {field: defaults.field, current: config};
108
        }
109
110
        config = Object.assign(defaults, config);
111
112
        var field = $(config.field),
113
            form = field.closest('form'), 
114
            selector = $('<ul class="org_openpsa_search_providers"></ul>'),
115
            li_class = '';
116
117
        function enable_provider(provider) {
118
            field
119
                .attr('placeholder', provider.placeholder || '')
120
                .focus();
121
            form.attr('action', provider.url);
122
123
            if (provider.autocomplete) {
124
                field.category_complete({
125
                    source: function (request, response) {
126
                        $.ajax({
127
                            url: provider.url + '/autocomplete/',
128
                            dataType: 'json',
129
                            data: {query: request.term},
130
                            success: response,
131
                            error: function(jqXHR, textStatus, errorThrown) {
132
                                field.trigger('autocompleteerror', [jqXHR, textStatus, errorThrown]);
133
                                response([]);
134
                            }
135
                        });
136
                    },
137
                    select: function (event, ui) {
138
                        if (ui.item) {
139
                            location.href = ui.item.url;
140
                        }
141
                    },
142
                    minLength: 2,
143
                    autoFocus: true
144
                });
145
            }
146
        }
147
148
        providers.forEach(function(provider) {
149
            li_class = 'provider';
150
            if (config.current === provider.identifier) {
151
                li_class += ' current';
152
                enable_provider(provider);
153
            }
154
155
            $('<li class="' + li_class + '">' + provider.placeholder + '</li>')
156
                .data('provider', provider)
157
                .click(function() {
158
                    var old_item = form.find('.org_openpsa_search_providers .current');
159
160
                    if (old_item.data('provider').autocomplete) {
161
                        field.category_complete('destroy');
162
                    }
163
164
                    old_item.removeClass('current');
165
                    $(this).addClass('current');
166
167
                    enable_provider(provider);
168
169
                    form.find('.org_openpsa_search_trigger').click();
170
171
                    $.post(MIDCOM_PAGE_PREFIX + '__mfa/asgard/preferences/ajax/', {openpsa2_search_provider: provider.identifier});
172
                })
173
                .appendTo(selector);
174
        });
175
176
        var search = location.search.replace(/^.*?[\?|&]query=([^&]*).*/, '$1');
177
        if (search !== '' && search !== location.search) {
178
            field.val(decodeURIComponent(search));
179
        }
180
181
        selector.insertBefore(field);
182
183
        $('<div class="org_openpsa_search_trigger"><i class="fa fa-search"></i></div>')
184
            .click(function() {
185
                form.find('.org_openpsa_search_providers').toggle();
186
                $(this).toggleClass('focused');
187
            })
188
            .insertBefore(field);
189
190
        field.show();
191
    }
192
};
193